package com.yiguantong.police.retrofit;


import com.MainApplication;
import com.yiguantong.police.ui.utils.HttpUtil;
import com.yiguantong.police.ui.utils.MyLog;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public abstract class CustomObserver implements Observer<ResponseBody> {

    public CustomObserver() {
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (!HttpUtil.isNetOk(MainApplication.getIns())) {
            d.dispose();
        }
    }

    @Override
    public void onNext(ResponseBody value) {
        try {
            String jsonString = value.string();
            jsonString = replaceBlank(jsonString);
            MyLog.i("CustomObserver onNext :" + jsonString);
            // 校验json数据格式
            if(jsonString != null && ((jsonString.startsWith("{") && jsonString.endsWith("}"))
                    || (jsonString.startsWith("[") && jsonString.endsWith("]"))) ) {
                onSuccess(jsonString);
            } else {
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public abstract void onSuccess(String jsonString);

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
    }

    @Override
    public void onComplete() {

    }

}
